package com.carrental.vehicle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.common.exception.BusinessException;
import com.carrental.vehicle.entity.VehicleBrand;
import com.carrental.vehicle.entity.VehicleSeries;
import com.carrental.vehicle.mapper.VehicleBrandMapper;
import com.carrental.vehicle.mapper.VehicleSeriesMapper;
import com.carrental.vehicle.service.VehicleBrandService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 车辆品牌服务实现类
 */
@Service
@RequiredArgsConstructor
public class VehicleBrandServiceImpl extends ServiceImpl<VehicleBrandMapper, VehicleBrand> implements VehicleBrandService {

    private final VehicleSeriesMapper vehicleSeriesMapper;

    /**
     * 根据ID获取品牌
     *
     * @param id 品牌ID
     * @return 品牌信息
     */
    @Override
    public VehicleBrand getBrandById(Long id) {
        VehicleBrand brand = getById(id);
        if (brand == null) {
            throw new BusinessException("品牌不存在");
        }
        return brand;
    }

    /**
     * 保存或更新品牌
     *
     * @param vehicleBrand 品牌信息
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateBrand(VehicleBrand vehicleBrand) {
        // 检查品牌名称是否重复
        LambdaQueryWrapper<VehicleBrand> queryWrapper = new LambdaQueryWrapper<VehicleBrand>()
                .eq(VehicleBrand::getName, vehicleBrand.getName())
                .eq(VehicleBrand::getDeleted, 0);
        
        if (vehicleBrand.getId() != null) {
            queryWrapper.ne(VehicleBrand::getId, vehicleBrand.getId());
        }
        
        long count = count(queryWrapper);
        if (count > 0) {
            throw new BusinessException("品牌名称已存在");
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        if (vehicleBrand.getId() == null) {
            // 新增
            vehicleBrand.setCreateTime(now);
            vehicleBrand.setUpdateTime(now);
            vehicleBrand.setDeleted(0);
            return save(vehicleBrand);
        } else {
            // 更新
            vehicleBrand.setUpdateTime(now);
            return updateById(vehicleBrand);
        }
    }

    /**
     * 删除品牌
     *
     * @param id 品牌ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBrandById(Long id) {
        // 检查品牌是否存在
        VehicleBrand brand = getById(id);
        if (brand == null) {
            throw new BusinessException("品牌不存在");
        }
        
        // 检查是否有关联的车辆系列
        long count = vehicleSeriesMapper.selectCount(new LambdaQueryWrapper<VehicleSeries>()
                .eq(VehicleSeries::getBrandId, id)
                .eq(VehicleSeries::getDeleted, 0));
        
        if (count > 0) {
            throw new BusinessException("该品牌下存在车辆系列，不能删除");
        }
        
        return removeById(id);
    }

    /**
     * 分页查询品牌
     *
     * @param page  分页参数
     * @param brand 查询条件
     * @return 分页结果
     */
    @Override
    public Page<VehicleBrand> pageBrand(Page<VehicleBrand> page, VehicleBrand brand) {
        LambdaQueryWrapper<VehicleBrand> queryWrapper = new LambdaQueryWrapper<>();
        
        queryWrapper.like(StringUtils.hasText(brand.getName()), VehicleBrand::getName, brand.getName())
                .like(StringUtils.hasText(brand.getCountry()), VehicleBrand::getCountry, brand.getCountry())
                .orderByDesc(VehicleBrand::getCreateTime);
        
        return page(page, queryWrapper);
    }

    /**
     * 获取所有品牌
     *
     * @return 品牌列表
     */
    @Override
    public List<VehicleBrand> listAllBrands() {
        return list(new LambdaQueryWrapper<VehicleBrand>()
                .eq(VehicleBrand::getDeleted, 0)
                .orderByAsc(VehicleBrand::getCreateTime));
    }
    
    /**
     * 获取所有可用的品牌（显示状态为1）
     *
     * @return 可用的品牌列表
     */
    @Override
    public List<VehicleBrand> listAvailableBrands() {
        return list(new LambdaQueryWrapper<VehicleBrand>()
                .eq(VehicleBrand::getDeleted, 0)
                .eq(VehicleBrand::getShowStatus, 1)
                .orderByAsc(VehicleBrand::getSort));
    }
} 